<template>
	<div class="tui-conversation-list">
		<ActionsMenu v-if="isShowOverlay" :selectedConversation="currentConversation"
			:actionsMenuPosition="actionsMenuPosition" :selectedConversationDomRect="currentConversationDomRect"
			@closeConversationActionMenu="closeConversationActionMenu" />
		<div v-for="(conversation, index) in imlist" :id="`convlistitem-${index}`" :key="index" :class="[
      'TUI-conversation-content',
      !isPC && 'TUI-conversation-content-h5',
    ]">
			<div @click="enterConversationChat(conversation.conversationID, conversation.account)"
				@longpress="showConversationActionMenu($event, conversation, index)"
				@contextmenu.prevent="showConversationActionMenu($event, conversation, index, true)" :class="[
          isPC && 'isPC',
          'TUI-conversation-item',
          currentConversationID === conversation.conversationID &&
          'TUI-conversation-item-selected',
          conversation.isPinned && 'TUI-conversation-item-pinned',
        ]">
				<aside class="left">
					<!-- <Avatar useSkeletonAnimation :url="conversation.getAvatar()" size="30px" /> -->
					<Avatar useSkeletonAnimation :url="conversation.faceurl" size="30px" />
					<div v-if="userOnlineStatusMap && isShowUserOnlineStatus(conversation)" :class="[
            'online-status',
            Object.keys(userOnlineStatusMap).length > 0 &&
              Object.keys(userOnlineStatusMap).includes(
                conversation.userProfile.userID
              ) &&
              userOnlineStatusMap[conversation.userProfile.userID]
                .statusType === 1
              ? 'online-status-online'
              : 'online-status-offline',
          ]"></div>
					<span class="num" v-if="conversation.unreadCount > 0 && !conversation.isMuted">
						{{
              conversation.unreadCount > 99 ? "99+" : conversation.unreadCount
            }}
					</span>
					<span class="num-notify" v-if="conversation.unreadCount > 0 && conversation.isMuted"></span>
				</aside>
				<div class="content">
					<div class="content-header">
						<label class="content-header-label">
							<!-- <p class="name">{{ conversation.getShowName() }}</p> -->
							<p class="name">{{ conversation.nick }}</p>
						</label>
						<div class="middle-box">
							<span class="middle-box-at" v-if="
                conversation.type === 'GROUP' &&
                conversation.groupAtInfoList &&
                conversation.groupAtInfoList.length > 0
              ">{{ conversation.getGroupAtInfo() }}</span>
							<p class="middle-box-content">
								{{ conversation.text || '' }}
							</p>
						</div>
					</div>
					<div class="content-footer">
						<span class="time">{{ conversation.time || '' }}</span>
						<Icon v-if="conversation.isMuted" :file="muteIcon"></Icon>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import {
		HTTP_REQUEST_URL,
	} from '@/config/app';

	interface IUserStatus {
		statusType : number;
		customStatus : string;
	}

	interface IUserStatusMap {
		[userID : string] : IUserStatus;
	}
	import { ref, computed } from "../../../adapter-vue";
	import TUIChatEngine, {
		TUIStore,
		StoreName,
		TUIConversationService,
	} from "@tencentcloud/chat-uikit-engine";
	import Icon from "../../common/Icon.vue";
	import Avatar from "../../common/Avatar/index.vue";
	import ActionsMenu from "../actions-menu/index.vue";
	import muteIcon from "../../../assets/icon/mute.svg";
	import { isPC, isH5, isUniFrameWork } from "../../../utils/env";
	import TencentCloudChat from '@tencentcloud/chat';
	import {
		TUIChatKit,
		genTestUserSig,
	} from "TUIKit";
	import store from '@/store/index.js';
	const emits = defineEmits(["handleSwitchConversation", "getPassingRef"]);
	const currentConversation = ref<IConversationModel>();
	const currentConversationID = ref<string>();
	const currentConversationDomRect = ref<DOMRect>();
	const isShowOverlay = ref<boolean>(false);
	const conversationList = ref<IConversationModel[]>([]);
	const imlist = ref<IConversationModel[]>([]);
	const mobile = uni.getStorageSync('mobile');
	uni.request({
		url: HTTP_REQUEST_URL + '/common/imlist',
		data: { mobile: mobile },
		header: {},
		success: (res) => {
			imlist.value = res.data.data;
		},
		fail: (err) => {

		}
	})
	console.log(conversationList)
	const conversationListDomRef = ref<HTMLElement | undefined>();
	const actionsMenuPosition = ref<{ top : number, left ?: number, conversationHeight ?: number }>({
		top: 0,
	});
	const displayOnlineStatus = ref(false); // 在线状态 默认关闭
	const userOnlineStatusMap = ref<IUserStatusMap>();

	let lastestOpenActionsMenuTime : number | null = null;

	TUIStore.watch(StoreName.CONV, {
		currentConversationID: (id : string) => {
			currentConversationID.value = id;
		},
		conversationList: (list : Array<IConversationModel>) => {
			conversationList.value = list;
		},
		currentConversation: (conversation : IConversationModel) => {
			currentConversation.value = conversation;
		},
	});

	// 初始状态
	TUIStore.watch(StoreName.USER, {
		displayOnlineStatus: (status : boolean) => {
			displayOnlineStatus.value = status;
		},
		userStatusList: (list : Map<string, IUserStatus>) => {
			if (list.size !== 0) {
				userOnlineStatusMap.value = [...list.entries()].reduce(
					(obj, [key, value]) => {
						obj[key] = value;
						return obj;
					},
					{} as IUserStatusMap
				);
			}
		},
	});

	const isShowUserOnlineStatus = (conversation : IConversationModel) : boolean => {
		return (
			displayOnlineStatus.value &&
			conversation.type === TUIChatEngine.TYPES.CONV_C2C
		);
	};

	const showConversationActionMenu = (
		event : Event,
		conversation : IConversationModel,
		index : number,
		isContextMenuEvent ?: boolean
	) => {
		if (isContextMenuEvent && isUniFrameWork) {
			return;
		}
		currentConversation.value = conversation;
		lastestOpenActionsMenuTime = Date.now();
		getActionsMenuPosition(event, index);
	};

	const closeConversationActionMenu = () => {
		// 防止连续触发overlay的tap事件
		if (
			lastestOpenActionsMenuTime &&
			Date.now() - lastestOpenActionsMenuTime > 300
		) {
			currentConversation.value = undefined;
			isShowOverlay.value = false;
		}
	};

	const getActionsMenuPosition = (event : Event, index : number, conversation ?: any) => {
		if (isUniFrameWork) {
			if (typeof conversationListDomRef.value === 'undefined') {
				emits('getPassingRef', conversationListDomRef);
			}
			const query = uni.createSelectorQuery().in(conversationListDomRef.value);
			query.select(`#convlistitem-${index}`).boundingClientRect(data => {
				if (data) {
					actionsMenuPosition.value = {
						// uni-h5的uni-page-head不被认为是视窗中的成员，因此手动上head的高度
						top: data.bottom + (isH5 ? 44 : 0),
						left: event.touches[0].pageX,
						conversationHeight: data.height,
					};
					isShowOverlay.value = true;
				}
			}).exec();
		} else {
			// 处理Vue原生
			const rect = event.currentTarget?.getBoundingClientRect();
			if (rect) {
				actionsMenuPosition.value = {
					top: rect.bottom,
					left: isPC ? event.clientX : undefined,
					conversationHeight: rect.height,
				};
			}
			isShowOverlay.value = true;
		}
	};

	const enterConversationChat = (conversationID : string, account : string) => {
		let chat = TencentCloudChat.create({
			SDKAppID: 1400818966 // Replace `0` with the `SDKAppID` of your Chat app during access.
		});
		// console.log(imlist);
		let promise1 = chat.logout();
		promise1.then(function (imResponse) {
			console.log(imResponse.data); // 登出成功
		}).catch(function (imError) {
			console.warn('logout error:', imError);
		});
		// TUIChatKit 初始化
		TUIChatKit.init();
		const config = {
			userID: account, // User ID
			SDKAppID: 1400818966, // Your SDKAppID
			secretKey: 'fbb62384b4544dbb81878e6af400affada719aecb9ddebe6c1221868f959635c', // Your secretKey
		};
		let Sig = genTestUserSig(config).userSig;
		console.log(config.userID)
		let promise = chat.login({ userID: config.userID, userSig: Sig });
		promise.then(function (imResponse) {
			console.log(imResponse.data); // 登录成功
			if (imResponse.data.repeatLogin === true) {
				// 标识账号已登录，本次登录操作为重复登录。
				console.log(imResponse.data.errorInfo);
			}
		}).catch(function (imError) {
			console.warn('login error:', imError); // 登录失败的相关信息
		});
		const chat1 = computed(() => { return store.state.im.chat });
		chat1.value.isReady();
		chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, function (event) {
			uni.request({
				url: HTTP_REQUEST_URL + '/common/imupdate',
				data: { text: event.data, to_user: config.userID },
				header: {},
				success: (res) => {
					imlist.value = res.data.data;
				},
				fail: (err) => {

				}
			})
	
			console.log("MESSAGE_RECEIVED", event);
			// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
			// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
			// event.data - 存储 Message 对象的数组 - [Message]
		});
		chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, function (event) {
			uni.request({
				url: HTTP_REQUEST_URL + '/common/imupdate',
				data: { unreadCount: event.data, to_user: config.userID },
				header: {},
				success: (res) => {
					imlist.value = res.data.data;
				},
				fail: (err) => {

				}
			})

			console.log("onTotalUnreadMessageCountUpdated", event);
		});
		chat.setLogLevel(4);
		store.commit('setImChat', chat)
		emits("handleSwitchConversation", conversationID);
		TUIConversationService.switchConversation(conversationID);
	};


	// 暴露给父组件，当监听到滑动事件时关闭actionsMenu
	defineExpose({ closeChildren: closeConversationActionMenu });
</script>

<style lang="scss" scoped src="./style/index.scss"></style>